package com.duan.common.handler;

import com.duan.common.beans.vo.ResponseVO;
import com.duan.common.exceptions.ServiceException;
import com.duan.common.utils.ResponseUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created by duanlsh on 18/6/20.
 */
@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {


    /**
     * 系统自带的异常信息处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseVO normalException(Exception e) {
        if (e instanceof IllegalArgumentException) {
            return ResponseUtil.fail(StringUtils.isEmpty(e.getMessage()) ? "参数有误" : e.getMessage());
        }
        log.error("GlobalExceptionHandler.normalException ", e);
        return ResponseUtil.fail();
    }


    /**
     * 自定义异常类信息
     * @param e
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    public ResponseVO personException(ServiceException e){
        log.error("GlobalExceptionHandler.personException ", e);
        if (e.getCode() == null) {
            return ResponseUtil.fail();
        }
        return ResponseUtil.fail(e.getCode(), e.getMessage());
    }


    @ExceptionHandler(value = BindException.class)
    public ResponseVO personException(BindException e){
        log.error("GlobalExceptionHandler.personException ", e);

        return ResponseUtil.fail(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseVO validException(MethodArgumentNotValidException e){
        log.info("GlobalExceptionHandler.validException", e);
        return ResponseUtil.fail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());

    }
}
